package com.ruoyi.boat.controller;

import com.ruoyi.boat.aop.AvoidDuplicate;
import com.ruoyi.boat.domain.Boat;
import com.ruoyi.boat.domain.Device;
import com.ruoyi.boat.domain.DeviceBoat;
import com.ruoyi.boat.dto.BoatDto;
import com.ruoyi.boat.dto.DeviceBoatDto;
import com.ruoyi.boat.service.IAlertService;
import com.ruoyi.boat.service.IBoatService;
import com.ruoyi.boat.service.IDeviceBoatService;
import com.ruoyi.boat.service.IDeviceService;
import com.ruoyi.boat.tcp.cache.WaveBoat;
import com.ruoyi.boat.tcp.cache.MyApplicationCache;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 波浪艇Controller
 *
 * @author ruoyi
 * @date 2023-07-31
 */
@Api("Boat管理")
@Controller
@Slf4j
@RequestMapping("/boat/boat")
public class BoatController extends BaseController {
    private String prefix = "boat/boat";

    @Autowired
    private IBoatService boatService;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private IDeviceBoatService deviceBoatService;

    @Autowired
    private IAlertService alertService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private MyApplicationCache myApplicationCache;

    @RequiresPermissions("boat:boat:view")
    @GetMapping()
    public String boat(ModelMap mmap) {
        mmap.put("deptList", deptService.selectDeptList(new SysDept()));
        return "boat/boat/boat";
    }

    /**
     * 查询波浪艇列表
     */
    @RequiresPermissions("boat:boat:list")
    @ApiOperation("获取Boat列表")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Boat boat) {
        startPage();
        List<Boat> list = boatService.selectBoatList(boat);
        return getDataTable(list);
    }

    /**
     * 导出波浪艇列表
     */
    @RequiresPermissions("boat:boat:export")
    @Log(title = "波浪艇", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @AvoidDuplicate
    @ResponseBody
    public AjaxResult export(Boat boat) {
        List<Boat> list = boatService.selectBoatList(boat);
        ExcelUtil<Boat> util = new ExcelUtil<Boat>(Boat.class);
        return util.exportExcel(list, "波浪艇数据");
    }

    /**
     * 新增波浪艇
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存波浪艇
     */
    @RequiresPermissions("boat:boat:add")
    @Log(title = "波浪艇", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Boat boat) {
        if(boat.getCode() == null){
            return AjaxResult.error("艇编号不能为空");
        }
        // 定义正则表达式
        String regex = "^(?:[0-9A-F]{2})$";
        // 编译正则表达式
        Pattern pattern = Pattern.compile(regex);
        // 创建Matcher对象
        Matcher matcher = pattern.matcher("FF");
        // 进行匹配
        if (!matcher.matches()) {
            return AjaxResult.error("艇编号不符合格式");
        }
        return toAjax(boatService.insertBoat(boat));
    }

    /**
     * 修改波浪艇
     */
    @RequiresPermissions("boat:boat:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        Boat boat = boatService.selectBoatById(id);
        mmap.put("boat", boat);
        return prefix + "/edit";
    }

    /**
     * 修改保存波浪艇
     */
    @RequiresPermissions("boat:boat:edit")
    @Log(title = "波浪艇", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Boat boat) {
        if(boat.getCard() != null){
            //更新card
            WaveBoat waveBoat = myApplicationCache.getWaveBoat(boat.getCode());
            if( waveBoat != null){
                waveBoat.getBoatInfo().setCard(boat.getCard());
                myApplicationCache.updateWaveBoat(boat.getCode(),waveBoat);
            }
        }
        return toAjax(boatService.updateBoat(boat));
    }

    /**
     * 修改波浪艇
     */
    @RequiresPermissions("boat:boat:edit")
    @GetMapping("/upload/{id}")
    public String upload(@PathVariable("id") Long id, ModelMap mmap) {
        Boat boat = boatService.selectBoatById(id);
        mmap.put("boat", boat);
        return prefix + "/upload";
    }

    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadSave(@RequestParam("file") MultipartFile file, Boat boat) throws IOException {
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        boat.setImg(fileName);
        // 删除老照片
        boolean result = boatService.deleteImgByBoatId(boat.getId());
        log.debug("deleteImgByBoatId: {}, result: {}", boat.getId(), result);
        return toAjax(boatService.updateBoat(boat));
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/img/{boatId}")
    public void resourceDownload(HttpServletRequest request, HttpServletResponse response, @PathVariable("boatId") Long boatId)
            throws Exception {
        Boat boat = boatService.selectBoatById(boatId);
        // 本地资源路径
        String filePath = RuoYiConfig.getProfile();
        // 数据库资源地址
        String downloadPath = filePath + StringUtils.substringAfter(boat.getImg(), Constants.RESOURCE_PREFIX);
        // 下载名称
        String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }

    /**
     * 删除波浪艇
     */
    @RequiresPermissions("boat:boat:remove")
    @Log(title = "波浪艇", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(boatService.deleteBoatByIds(ids));
    }

    /**
     * 获取所有艇dto
     *
     * @return
     */
    @RequiresPermissions("boat:boat:list")
    @ApiOperation("获取BoatDto列表")
    @RequestMapping("/all")
    @ResponseBody
    public AjaxResult getAllDto() {
        List<BoatDto> boatDtoList = boatService.selectBoatList(new Boat())
                .stream().map(boat -> boatService.selectBoatDto(boat.getId())).collect(Collectors.toList());
        return AjaxResult.success(boatDtoList);
    }

    /**
     * 分配设备界面
     *
     * @param mmap
     * @return
     */
    @RequiresPermissions("boat:boat:device")
    @GetMapping("/device/{boatId}")
    public String device(ModelMap mmap, @PathVariable Long boatId) {
        mmap.put("boat", boatService.selectBoatById(boatId));
        mmap.put("deviceList", deviceService.selectDeviceList(new Device()));
        mmap.put("deviceIdList", deviceBoatService.selectDeviceIdListByBoatId(boatId));
        return "boat/boat/device";
    }

    /**
     * 保存设备分配
     */
    @RequiresPermissions("boat:boat:device")
//    @Log(title = "波浪艇", businessType = BusinessType.INSERT)
    @PostMapping("/device")
    @ResponseBody
    public AjaxResult device(DeviceBoatDto deviceBoatDto) {
        Long boatId = deviceBoatDto.getBoatId();
        List<Long> devices = deviceBoatDto.getDevices();
        deviceBoatService.deleteDeviceBoatByBoatId(boatId);
        if (devices != null && !devices.isEmpty()) {
            for (Long deviceId : devices) {
                deviceBoatService.insertDeviceBoat(new DeviceBoat().setBoatId(boatId).setDeviceId(deviceId));
            }
        }
        return AjaxResult.success();
    }

}
